/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xuexiang.xuidemo.provider;

import ohos.agp.colors.RgbColor;
import ohos.agp.colors.RgbPalette;
import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.components.element.VectorElement;
import ohos.agp.render.BlendMode;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;

import com.xuexiang.xui_lib.component.layout.ExpandableLayout;
import com.xuexiang.xui_lib.util.ImageTint;
import com.xuexiang.xuidemo.ResourceTable;
import com.xuexiang.xuidemo.slice.layout.expandable.ExpandableRecycleViewSlice;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

/**
 * 在RecycleView中使用adapter
 *
 * @since 2021-04-08
 */
public class ExpandableListAdapter extends BaseItemProvider {
    private static final int SELECT_ITEM_DEF = -1;
    /**
     * 默认旋转角度
     */
    private static final int DEFAULT_ROTATION_ANGLE = 90;
    /**
     * 动画默认执行时间
     */
    private static final int DEFAULT_ANIMATION_TIME = 300;
    /**
     * 当前点击的条目
     */
    private int mSelectPosition = SELECT_ITEM_DEF;

    private ExpandableRecycleViewSlice mSlice;
    private ListContainer mRecyclerView;
    private List<String> mList;

    /**
     * 构造方法
     *
     * @param slice 上下文
     * @param recyclerView 控件
     * @param data 数据集
     */
    public ExpandableListAdapter(ExpandableRecycleViewSlice slice, ListContainer recyclerView, List<String> data) {
        this.mSlice = slice;
        this.mList = data;
        this.mRecyclerView = recyclerView;
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        final Component cpt;
        ViewHolder viewHolder;
        if (component == null) {
            cpt = LayoutScatter.getInstance(mSlice)
                .parse(ResourceTable.Layout_adapter_expandable_list_item, null, false);
            viewHolder = new ViewHolder(cpt);
            cpt.setTag(viewHolder);
        } else {
            cpt = component;
            viewHolder = (ViewHolder) cpt.getTag();
        }

        // 设置矢量图图片着色
        VectorElement vectorElement = new VectorElement(mSlice, ResourceTable.Graphic_ic_arrow_right);
        ImageTint.setImageTint(viewHolder.ivIndicator, vectorElement,
            RgbPalette.parse("#2A9CDC"), BlendMode.SRC_IN);

        viewHolder.expandableLayout.setOnExpansionChangedListener((expansion, state) -> {
            if (mRecyclerView != null && state == ExpandableLayout.State.EXPANDING) {
                mRecyclerView.scrollTo(position);
            }
            if (viewHolder.ivIndicator != null) {
                viewHolder.ivIndicator.setRotation(expansion * DEFAULT_ROTATION_ANGLE);
            }
        });

        boolean isSelected = position == mSelectPosition;
        viewHolder.expandableLayout.setExpanded(isSelected, false);

        // 设置item点击状态背景色
        viewHolder.flTitle.setSelected(isSelected);
        ShapeElement shapeElement = new ShapeElement();
        if (isSelected) {
            shapeElement.setRgbColor(new RgbColor(242, 246, 249));
        } else {
            shapeElement.setRgbColor(RgbPalette.WHITE);
        }
        viewHolder.flTitle.setBackground(shapeElement);
        String title = getString(ResourceTable.String_item_example_number_title);
        String content = getString(ResourceTable.String_item_example_number_abstract);
        viewHolder.tvTitle.setText(String.format(Locale.ROOT, title, position + 1));
        viewHolder.tvContent.setText(String.format(Locale.ROOT, content, position + 1));
        viewHolder.flTitle.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                onClickItem(component, viewHolder.expandableLayout, position);
                ShapeElement shapeElement1 = new ShapeElement();
                if (viewHolder.expandableLayout.isExpanded()) {
                    shapeElement1.setRgbColor(new RgbColor(242, 246, 249));
                    viewHolder.flTitle.setBackground(shapeElement1);
                } else {
                    shapeElement1.setRgbColor(RgbPalette.WHITE);
                    viewHolder.flTitle.setBackground(shapeElement1);
                }
            }
        });

        return cpt;
    }

    private void onClickItem(Component view, final ExpandableLayout expandableLayout, final int position) {
        Component component = mRecyclerView.getComponentAt(position);
        if (component != null) {
            DependentLayout componentById = (DependentLayout) component.findComponentById(ResourceTable.Id_fl_title);
            componentById.setSelected(false);
            ExpandableLayout expandableLayout1 = (ExpandableLayout) component
                .findComponentById(ResourceTable.Id_expandable_layout);
            expandableLayout1.collapse(false);
        }

        if (position == mSelectPosition) {
            mSelectPosition = SELECT_ITEM_DEF;
        } else {
            view.setSelected(true);
            expandableLayout.expand(false);
            mSelectPosition = position;
        }
        notifyDataChanged();
    }

    /**
     * holder
     *
     * @since 2021-04-08
     */
    static class ViewHolder {
        ExpandableLayout expandableLayout;
        Image ivIndicator;
        Text tvTitle;
        Text tvContent;
        DependentLayout flTitle;

        private ViewHolder(Component component) {
            expandableLayout = (ExpandableLayout) component.findComponentById(ResourceTable.Id_expandable_layout);
            ivIndicator = (Image) component.findComponentById(ResourceTable.Id_iv_indicator);
            tvTitle = (Text) component.findComponentById(ResourceTable.Id_tv_title);
            tvContent = (Text) component.findComponentById(ResourceTable.Id_tv_content);
            flTitle = (DependentLayout) component.findComponentById(ResourceTable.Id_fl_title);
        }
    }

    /**
     * 返回对资源id对应的字符串
     *
     * @param id 资源ID
     * @return String字符串
     */
    public String getString(int id) {
        try {
            return mSlice.getResourceManager().getElement(id).getString();
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.printStackTrace();
        }
        return "";
    }
}
